from rest_framework import serializers
from django.core.cache import cache
from product.models import Contact


class ContactSerializer(serializers.ModelSerializer):
    address = serializers.CharField(required=False, label='联系地址')
    your_name = serializers.CharField(required=False, label='你的名字')
    code = serializers.CharField(required=True, write_only=True, max_length=4, min_length=4, label="验证码",
                                 error_messages={
                                     "blank": "请输入验证码",
                                     "required": "请输入验证码",
                                     "max_length": "验证码格式错误",
                                     "min_length": "验证码格式错误"
                                 },
                                 help_text="验证码")

    verifyCode_key = serializers.CharField(required=True, write_only=True, label="验证码key",
                                           error_messages={
                                               "required": "请输入验证码",
                                           })

    def validate(self, attrs):
        verifyCode_key = attrs["verifyCode_key"]
        code = attrs["code"]
        cache_code = cache.get(verifyCode_key)
        if cache_code != code:
            raise serializers.ValidationError("验证码错误")
        del attrs["verifyCode_key"]
        del attrs["code"]
        return attrs

    class Meta:
        model = Contact
        fields = ("customer_name","address","your_name","mobile", "code", "verifyCode_key")